<template>
    <div class="divBox">
      <el-card class="box-card">
        <el-form
          ref="editPram"
          :model="editPram"
          :rules="rules"
          label-width="130px"
        >
          <el-form-item label="权益名称" prop="name">
            <el-input
              v-model="editPram.name"
              placeholder="请输入权益名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="选择权益类型" prop="type">
            <el-select
              v-model="editPram.type"
              placeholder="请选择"
              @change="typeChange"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="权益描述" prop="description">
            <el-input
              v-model="editPram.description"
              placeholder="请输入权益描述"
            ></el-input>
          </el-form-item>
          <el-form-item label="权益图片" prop="img">
            <el-input
              v-model="editPram.img"
              placeholder="请输入权益图片"
            ></el-input>
          </el-form-item>
          <el-form-item label="商家" prop="shopId">
            <el-select
              v-model="editPram.shopId"
              clearable
              placeholder="请选择商家"
              @change="shopChange"
            >
              <el-option
                v-for="item in shopList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="小程序" prop="wxId">
            <el-select
              v-model="editPram.wxId"
              clearable
              placeholder="请选择小程序"
            >
              <el-option
                v-for="item in wxList"
                :key="item.appid"
                :label="item.name"
                :value="item.appid"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-if="editPram.type == 2" label="选择商品&折扣：">
            <div style="display: flex">
              <el-select
                style="width: 400px"
                v-model="discount_product_id"
                clearable
                placeholder="请选择商品"
                @change="chooseGood"
              >
                <el-option
                  v-for="item in goodList"
                  :key="item.id"
                  :label="item.storeName"
                  :value="item.id"
                >
                </el-option>
              </el-select>
              <el-input
                v-model="discount_part"
                placeholder="请输入商品折扣"
                type="text"
                onKeypress="return(/^[0-9]*$/.test(String.fromCharCode(event.keyCode)))"
              >
                <i slot="suffix">%</i></el-input
              >
              <el-button type="primary" size="mini" @click="addGood"
                >添加</el-button
              >
            </div>
            <el-table
              :data="addList"
              size="mini"
              class="table"
              highlight-current-row
              :header-cell-style="{ fontWeight: 'bold' }"
            >
              <el-table-column prop="storeName" label="名称" min-width="200" />
              <el-table-column prop="discount" label="折扣%" min-width="100" />
              <el-table-column
                label="操作"
                min-width="100"
                fixed="right"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handlerDelete(scope.$index)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
          <el-form-item
            v-if="editPram.type == 1"
            label="整单折扣"
            prop="discount"
          >
            <el-input
              v-model="editPram.discount"
              placeholder="请输入整单折扣"
              type="text"
              onKeypress="return(/^[0-9]*$/.test(String.fromCharCode(event.keyCode)))"
            >
              <i slot="suffix">%</i></el-input
            >
          </el-form-item>
          <div class="submit_btn">
            <el-button
              type="primary"
              size="mini"
              @click="handlerSubmit('editPram')"
              >提交</el-button
            >
          </div>
        </el-form>
      </el-card>
    </div>
  </template>
  <script>
  import { productListApi } from "@/api/store";
  import { addQuanyi, updateQuanyi } from "@/api/quanyi";
  import { shopListApi } from "@/api/shopPoint";
  import { typeList, wxList } from "@/utils/constants.js";
  export default {
    // name: 'QuanyiSet',
    props: {
      prent: {
        type: Object,
        required: true,
      },
      isCreate: {
        type: Number,
        default: 0,
      },
      editData: {
        type: Object,
      },
    },
    data() {
      return {
        loadingBtn: false,
        editPram: {
          description: null,
          discount: null,
          name: null,
          productDiscount: null,
          shopId: null,
          type: null,
          img: null,
        },
        temp_good: null,
        temp_type_id: null,
  
        discount_product_id: null,
        discount_part: null, //整单折扣
        addList: [],
        shopList: [],
        goodList: [],
  
        typeList,
        wxList,
        rules: {
          name: [{ required: true, message: "请输入权益名称", trigger: "blur" }],
          type: [
            { required: true, message: "请输入权益类型", trigger: "change" },
          ],
          wxId: [
            { required: true, message: "请输入小程序", trigger: "change" },
          ],
          description: [
            { required: true, message: "请输入权益描述", trigger: "blur" },
          ],
          // img: [
          //     { required: true, message: '请输入权益图片', trigger: 'blur' }
          // ],
  
          shopId: [
            { required: true, message: "请选择选择商家", trigger: "change" },
          ],
          discount: [
            { required: true, message: "请输入整单折扣", trigger: "blur" },
          ],
        },
      };
    },
    mounted() {
      this.initEditData();
    },
    methods: {
      initEditData() {
        this.getShopList();
        const {
          id,
          description,
          discount,
          name,
          productDiscount,
          shopId,
          type,
          // img,
        } = this.editData;
        if (this.isCreate === 1) {
          this.editPram.id = id;
          this.editPram.description = description;
          this.editPram.discount = discount;
          this.editPram.name = name;
          this.editPram.productDiscount = productDiscount;
          this.editPram.shopId = Number(shopId);
          this.editPram.type = type;
          // this.editPram.img = img;
          this.shopChange(shopId);
        }
      },
      getShopList() {
        shopListApi({
          page: 1,
          limit: 100,
          status: 1,
          temp: new Date().getTime(),
        }).then((res) => {
          this.shopList = res.list;
        });
      },
      shopChange(e) {
        if (this.editPram.type == 2) {
          productListApi({
            type: 1,
            shopId: e,
            page: 1,
            limit: 100,
          }).then((res) => {
            this.goodList = res.list;
          });
        }
      },
      handlerSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (!valid) return;
          if (this.editPram.type == 2 && this.addList.length == 0) {
            return this.$message.error("请添加折扣商品");
          }
          if (this.editPram.type == 1) {
            // 整单
            if (
              parseInt(this.editPram.discount) <= 9 ||
              parseInt(this.editPram.discount) >= 1
            ) {
            } else {
              return this.$message.error("请输入正确的折扣");
            }
          }
          if (this.editPram.type == 2) {
            // 折扣
            this.editPram.productDiscount = this.addList.map((item) => {
              return {
                productId: item.id,
                discount: item.discount,
              };
            });
          }
          this.handlerSaveOrUpdate(this.isCreate === 0);
        });
      },
      handlerSaveOrUpdate(isSave) {
        this.loadingBtn = true;
        if (isSave) {
          addQuanyi(this.editPram)
            .then((data) => {
              this.$emit("hideEditDialog");
              this.$message.success("创建成功");
              this.loadingBtn = false;
              this.$router.push({ path: '/quanyi/list' });
            })
            .catch(() => {
              this.loadingBtn = false;
            });
        } else {
          updateQuanyi(this.editPram, this.editPram.id)
            .then((data) => {
              this.$emit("hideEditDialog");
              this.$message.success("更新成功");
              this.$router.push({ path: '/quanyi/list' });
              this.loadingBtn = false;
            })
            .catch(() => {
              this.loadingBtn = false;
            });
        }
      },
      addGood() {
        if (this.temp_good && this.discount_part) {
          if (
            parseInt(this.discount_part) <= 9 ||
            parseInt(this.discount_part) >= 1
          ) {
            this.addList.push({
              ...this.temp_good,
              discount: this.discount_part,
            });
            this.temp_good = null;
            this.discount_part = null;
            this.discount_product_id = null;
          } else {
            this.$message.error("请输入正确的折扣");
          }
        } else {
          this.$message.error("请输入商品或者折扣");
        }
      },
      chooseGood(e) {
        for (let i = 0; i < this.goodList.length; i++) {
          if (this.goodList[i].id == e) {
            this.temp_good = this.goodList[i];
          }
        }
      },
  
      handlerDelete(index) {
        this.$confirm("确定删除当前数据", "提示").then((result) => {
          this.addList.splice(index, 1);
          this.$message.success("删除数据成功");
        });
      },
  
      typeChange(e) {
        this.temp_type_id = e;
        // 改变了
        if (e == 3) {
          this.addList = [];
          this.discount_product_id = null;
          this.discount_part = null;
          this.editPram.discount = null;
          this.editPram.productDiscount = null;
        }
        if (e == 1) {
          // 整单
          this.addList = [];
          this.discount_product_id = null;
          this.discount_part = null;
          this.editPram.productDiscount = null;
        }
        if (e == 2) {
          // 商品折扣
          this.editPram.discount = null;
        }
        if (this.goodList.length == 0 && this.editPram.shopId) {
          this.shopChange(this.editPram.shopId);
        }
      },
    },
  };
  </script>
  
  <style lang="scss" scoped>
  .submit_btn {
    display: flex;
    justify-content: flex-end;
  }
  </style>